<template>
    <div class="inventory-management">
        <el-form>
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-form-item label="选择时间">
                        <el-date-picker v-model="date" type="date" placeholder="选择日期" format="YYYY-MM-DD"
                            value-format="YYYY-MM-DD" />
                    </el-form-item>
                </el-col>
                <el-col :span="18">
                    <!-- <el-card class="mb-4"> -->
                    <div class="buttonClass">
                        <el-button type="primary" @click="handleQuery">查询</el-button>
                        <el-button type="primary" @click="handleAdd">新增</el-button>
                        <el-button type="primary">
                            <el-upload type="primary" :show-file-list="false" :action="`/api/inoutinventory/import`"
                                :headers="headers" :on-success="onSuccess">导入</el-upload>
                        </el-button>
                        <el-button type="primary" @click="handleExport">导出</el-button>
                    </div>
                    <!-- </el-card> -->
                </el-col>
            </el-row>
        </el-form>

        <el-table :data="tableData" style="width: 100%">
            <el-table-column type="index" label="序号" width="100" />
            <el-table-column prop="categoryName" label="品类名称" />
            <el-table-column prop="unit" label="单位" />
            <el-table-column prop="specification" label="规格" />
            <el-table-column prop="date" label="进出库日期" />
            <el-table-column prop="inStock" label="进库量" />
            <el-table-column prop="outStock" label="出库量" />
            <el-table-column prop="purchasePrice" label="单价" />
            <el-table-column prop="totalPrice" label="总价" />
            <el-table-column prop="vendor" label="供应商" />
            <el-table-column prop="address" label="仓库" />
            <el-table-column label="操作">
                <template #default="scope">
                    <el-button link type="primary" size="small" @click="handleEdit(scope.row)"
                        :disabled="user.status == 2">修改</el-button>
                    <el-button link type="danger" size="small" @click="handleDelete(scope.row)"
                        :disabled="user.status == 2">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <div class="flex justify-between items-center mt-4">
            <span class="text-sm text-gray-500">
                共 {{ total }} 条记录 第 {{ currentPage }} / {{ totalPages }} 页
            </span>
            <el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10, 15]"
                :small="small" :disabled="disabled" :background="background"
                layout="total, prev, pager, next, sizes, jumper" :total="total" @size-change="handleSizeChange"
                @current-change="handleCurrentChange" />
        </div>
        <el-dialog v-model="dialogVisible" title="新增商品" width="50%">
            <el-form :model="form" label-width="120px">
                <el-form-item label="一级目录">
                    <el-select v-model="form.firstLevel" filterable remote reserve-keyword clearable
                        placeholder="Please enter a keyword" :loading="loading" :remote-method="remoteMethodF"
                        @change="changeF" style="width: 240px">
                        <el-option v-for="item in optionsF" :key="item.id" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="二级目录">
                    <el-select v-model="form.secondLevel" filterable remote reserve-keyword clearable
                        :disabled="form.firstLevel == '' || form.categoryName != ''"
                        placeholder="Please enter a keyword" :loading="loading" style="width: 240px">
                        <el-option v-for="item in optionsS" :key="item.id" :label="item.name" :value="item.name" />
                    </el-select>
                </el-form-item>
                <el-form-item label="品类名称">
                    <el-select v-model="form.categoryName" filterable remote reserve-keyword clearable
                        placeholder="Please enter a keyword" :loading="loading" :remote-method="remoteMethodC"
                        @change="changeC" style="width: 240px">
                        <el-option v-for="item in optionsC" :key="item.id" :label="item.categoryName"
                            :value="item.categoryName" />
                    </el-select>
                </el-form-item>
                <el-form-item label="单位">
                    <el-input v-model="form.unit" disabled />
                </el-form-item>
                <el-form-item label="规格">
                    <el-input v-model="form.specification" disabled />
                </el-form-item>
                <el-form-item label="进出库日期">
                    <el-date-picker v-model="form.date" type="date" placeholder="选择日期" format="YYYY/MM/DD"
                        value-format="YYYY-MM-DD" />
                </el-form-item>
                <el-form-item label="进库量">
                    <el-input-number v-model="form.inStock" :min="0" :precision="2" />
                </el-form-item>
                <el-form-item label="出库量">
                    <el-input-number v-model="form.outStock" :min="0" :precision="2" />
                </el-form-item>
                <el-form-item label="价格">
                    <el-input-number v-model="form.purchasePrice" :min="0" :precision="2" />
                </el-form-item>
                <el-form-item label="库存地">
                    <el-select v-model="form.address" filterable remote reserve-keyword clearable
                        placeholder="Please enter a keyword" :loading="loading" :remote-method="remoteMethodA"
                        style="width: 240px">
                        <el-option v-for="item in optionsA" :key="item.id" :label="item.address"
                            :value="item.address" />
                    </el-select>
                </el-form-item>
                <el-form-item label="供应商">
                    <el-select v-model="form.vendor" filterable remote reserve-keyword clearable
                        placeholder="Please enter a keyword" :loading="loading" :remote-method="remoteMethodV"
                        style="width: 240px">
                        <el-option v-for="item in optionsV" :key="item.id" :label="item.vendor" :value="item.vendor" />
                    </el-select>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { getInoutinventoryPage, findAllCategory, getLevelFirst, searchLevel, addInoutinventory, findAllVendor, findAllWarehouse, updateInoutinventory, delInoutinventory } from '@/utils/category'
import { ElMessage } from 'element-plus';

const date = ref(new Date().toLocaleDateString().replace(/\//g, '-'))
const dialogVisible = ref(false)
const user = ref(localStorage.getItem("user") ? JSON.parse(localStorage.getItem("user")) : {})
const form = ref({
    categoryName: '',
    unit: '',
    specification: '',
    date: '',
    inStock: 0,
    outStock: 0,
    purchasePrice: 0,
    secondLevel: '',
    firstLevel: '',
    vendor: '',
    address: ''
})
const formR = ref({
    categoryName: '',
    unit: '',
    specification: '',
    date: '',
    inStock: 0,
    outStock: 0,
    purchasePrice: 0,
    secondLevel: '',
    firstLevel: '',
    vendor: '',
    address: ''
})
const tableData = ref([])

const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(400)
const loading = ref(false)
const optionsF = ref([])
const optionsS = ref([])
const optionsC = ref([])
const optionsA = ref([])
const optionsV = ref([])
const operation = ref(1)

const totalPages = computed(() => Math.ceil(total.value / pageSize.value))

const search = () => {
    getInoutinventoryPage({ date: date.value }, currentPage.value, pageSize.value).then(res => {
        if (res.code == 200) {
            tableData.value = res.data.records
            total.value = res.data.total
        } else {
            ElMessage.error(res.message)
        }
    })
}

onMounted(() => {
    search()
})

const handleQuery = () => {
    search()
}

const onSuccess = (res) => {
    if (res.code == 200) {
        ElMessage.success('导入成功')
    } else {
        const message = (res.data.仓库地不存在 ? ('仓库地不存在:分别为' + res.data.仓库地不存在.map(num => `${num}行`).join(', ') + '\n') : '') + (res.data.品类管理中未查询到进出库记录中的信息 ? ('品类管理中未查询到进出库记录中的信息:分别为' + res.data.品类管理中未查询到进出库记录中的信息.map(num => `${num}行`).join(', ') + '\n') : '') + (res.data.进出库记录时间大于30天 ? ('进出库记录时间大于30天:分别为' + res.data.进出库记录时间大于30天.map(num => `${num}行`).join(', ') + '\n') : '') + (res.data.供应商不存在 ? ('供应商不存在:分别为' + res.data.供应商不存在.map(num => `${num}行`).join(', ') + '\n') : '')
        ElMessage({
            message: message,
            type: 'error',
            showClose: true,
            duration: 0// 消息显示5秒
        })
    }
}

const handleAdd = () => {
    operation.value = 1
    dialogVisible.value = true
    form.value = formR.value
}

const handleImport = () => {
    ElMessage.success('点击了导入按钮')
}

const handleExport = () => {
    window.location.href = `/api/inoutinventory/inoutexport/?date=${date.value}`
}

const submitForm = () => {
    if (operation.value == 1) {
        addInoutinventory(form.value).then(res => {
            if (res.code == 200) {
                dialogVisible.value = false
                search()
            } else {
                ElMessage.error(res.message)
            }
        })
    } else {
        updateInoutinventory(form.value).then(res => {
            if (res.code == 200) {
                dialogVisible.value = false
                search()
            } else {
                ElMessage.error(res.message)
            }
        })
    }
}

const handleEdit = (row) => {
    dialogVisible.value = true
    form.value = JSON.parse(JSON.stringify(row))
    operation.value = 2
}

const handleDelete = (row) => {
    ElMessageBox.confirm(
        '确认删除该记录吗？',
        '警告',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }
    )
        .then(() => {
            delInoutinventory(row.id).then(res => {
                if (res.code == 200) {
                    ElMessage.success(`删除记录: ${row.categoryName}`)
                    search()
                } else {
                    ElMessage.error(res.message)
                }
            })
        })
        .catch(() => {
            ElMessage.info('已取消删除')
        })
}

const handleSizeChange = (val) => {
    pageSize.value = val
    search()
}

const handleCurrentChange = (val) => {
    currentPage.value = val
    search()
}

const remoteMethodF = (query) => {
    loading.value = true
    setTimeout(() => {
        loading.value = false
        getLevelFirst({ firstLevel: query }).then(res => {
            if (res.code == 200) {
                optionsF.value = res.data.filter((item) => {
                    return item.name.toLowerCase().includes(query.toLowerCase())
                })
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}

const remoteMethodC = (query) => {
    loading.value = true
    setTimeout(() => {
        findAllCategory({ firstLevel: form.value.firstLevel, secondLevel: form.value.secondLevel, categoryName: query }).then(res => {
            if (res.code == 200) {
                loading.value = false
                optionsC.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}

const remoteMethodA = (query) => {
    loading.value = true
    setTimeout(() => {
        findAllWarehouse().then(res => {
            if (res.code == 200) {
                loading.value = false
                optionsA.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}

const remoteMethodV = (query) => {
    loading.value = true
    setTimeout(() => {
        findAllVendor().then(res => {
            if (res.code == 200) {
                loading.value = false
                optionsV.value = res.data
            } else {
                ElMessage.error(res.message)
            }
        })
    }, 200)
}

const changeF = () => {
    form.value.secondLevel = ''
    searchLevel({ name: form.value.firstLevel }).then(res => {
        if (res.code == 200) {
            optionsS.value = res.data[0].children
        } else {
            ElMessage.error(res.message)
        }
    })
}

const changeC = (name) => {
    optionsC.value.forEach(element => {
        if (element.categoryName == name) {
            form.value.firstLevel = element.firstLevel
            form.value.secondLevel = element.secondLevel
            form.value.specification = element.specification
            form.value.unit = element.unit
        }
    });
    searchLevel({ name: form.value.firstLevel }).then(res => {
        if (res.code == 200) {
            optionsS.value = res.data[0].children
        } else {
            ElMessage.error(res.message)
        }
    })
}
</script>

<style scoped>
.el-pagination {
    float: right;
}
</style>
<style>
.el-message {
    white-space: break-spaces;
}
</style>